<template>
	<div id="userLayout">
		<div style="display: none;">
			<input type="text" name="userName"/>
			<input type="password" name="userName"/>
		</div>
		<div class="login_panle">
			<div class="loginTop">
				<div class="login-logo">
					<img src="/src/assets/xlogo.png" alt="">
					<span>种植管理系统</span>
				</div>
			</div>
			<div class="loginMain">
				<div class="login_panle_form">
					<div class="login_panle_form_title">
						<span>欢迎登录</span>
					</div>
					<el-form ref="loginForm" :model="loginFormData" :rules="rules" @keyup.enter="submitForm">
						<el-form-item prop="userName">
							<div class="fmItemName">账号</div>
							<el-input v-model="loginFormData.userName" clearable placeholder="请输入用户名">
							</el-input>
						</el-form-item>
						<el-form-item prop="password">
							<div class="fmItemName">密码</div>
							<el-input v-model="loginFormData.password" clearable type="password" placeholder="请输入密码">
							</el-input>
						</el-form-item>
						<el-form-item>
							<div class="uhopbox">
								<div class="rmps">
									<el-checkbox  v-model="forgetChecked">记住密码</el-checkbox>
								</div>
								<div class="forget" @click="showDialog=true">忘记密码</div>
							</div>
						</el-form-item>
						<el-form-item>
							<el-button class="logBtn" type="primary" size="large" style="width: 46%; margin-left: 0" @click="submitForm">登
								录</el-button>
						</el-form-item>
						
					</el-form>
				</div>
			</div>

		</div>
		<div class="copyright">版权归：了了（重庆）农业科技有限公司</div>

		<teleport to='body'>
			<el-dialog custom-class="loginDgBox" 
			v-model="showDialog" 
			title="" 
			:show-close="true" 
			:close-on-press-escape="false" 
			:close-on-click-modal="false" 
			@close="stepFlag=1"
			>
				<div class="fgDgBox">
					<div class="dgTitle"><span>{{stepFlag==1?'忘记密码':'重设密码'}}</span></div>
					<div class="fgDgMain">
						<phone-code v-if="stepFlag==1" @next="goNext"/>
						<set-password v-else-if="stepFlag==2" :phone="f_phone" @confirm="showDialog=false"/>
					</div>
				</div>
			</el-dialog>
		</teleport>
	</div>
</template>

<script>
export default {
	name: 'Login',
}
</script>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { login } from '@/api/user'
import { getTeamFarmList } from '@/api/plant'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
import { message } from '@/utils/element'
import phoneCode from './components/phoneCode.vue'
import setPassword from './components/setPassword.vue'
const router = useRouter()

const userStore = useUserStore()

// 验证函数
const checkuserName = (rule, value, callback) => {
  if (value.length < 2) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule, value, callback) => {
  if (value.length < 3) {
    return callback(new Error('请输入正确的密码'))
  } else {
    callback()
  }
}

const loginForm = ref(null)
const forgetChecked = ref(false)
const showDialog = ref(false)
const stepFlag = ref(1)
const f_phone = ref('')

const loginFormData = ref({
  userName:'', //import.meta.env.VITE_USER_NAME,
  password: '',//import.meta.env.VITE_PASSWORD
})

const rules = reactive({
  userName: [{
    validator: checkuserName,
    trigger: 'blur'
  }],
  password: [{
    validator: checkPassword,
    trigger: 'blur'
  }]
})

onMounted(()=>{
	// 读取缓存
	let cachUserInfo = localStorage.getItem('lgUser')
	if(cachUserInfo){
		loginFormData.value = JSON.parse(cachUserInfo)
		forgetChecked.value = true
	}
})

const goLogin = async() => {
  const res = await login({ loginType: 'farm', rememberMe: true, ...loginFormData.value })
  if (res.success) {
    // userStore.setToken(res.data.token)
    const permissions = res.permissions ? res.permissions.split(',') : []
    const permissionArr = []
    permissions.forEach(item => {
      permissionArr.push(item.split('-')[0]) // 存储权限模块编号（每一个菜单或者操作按钮都对应一个编号）
    })

    // 获取登录用户公司农场列表
    // const res2 = await getFarmList({ companyId: res.companyId ,isEnable:true})
	const res2 = await getTeamFarmList(res.companyId)
    let farmId = ''; let farmList = ''
    if (res2.data && res2.data.length > 0) {
      farmList = res2.data
      // 默认第1个农场
      farmId = res2.data[0].farmId
    }

    userStore.setUserInfo({ ...res, permissionArr, loginTime: new Date(), farmId, farmList })
    
    // 记住密码处理
		if(forgetChecked.value){
			localStorage.setItem('lgUser',JSON.stringify({
				userName:loginFormData.value.userName,
				password:loginFormData.value.password
			}))
		}else{
			localStorage.removeItem('lgUser')
		}

    router.push('/manage/plan/list')
  } else {
    message(res.message, 3)
  }
}

const submitForm = () => {
  loginForm.value.validate(async(v) => {
    if (v) {
      goLogin()
    } else {
    //   message('请正确填写登录信息', 3)
      loginFormData.captchaValue = ''
      return false
    }
  })
}

const goNext = (phone)=>{
	f_phone.value = phone
	stepFlag.value = 2
}

// 动态添加路由
const addRouter = () => {
  router.addRoute(
    {
      path: '/11',
      name: '11',
      hidden: true,
      component: () => import('@/view/error/index.vue'),
      meta: { title: '11' }
    }
  )
}

</script>

<style lang="scss" scoped>
@import "@/style/newLogin.scss";
</style>
<style lang="scss">
.login_panle{
	.el-input__inner{
		height: 52px !important; // 50px
		background: #FFFFFF;
		border-radius: 5px;
		border: 2px solid transparent;
		font-size: 16px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 600;
		color: #333333;
	}
	.el-form-item__error{
		font-size: 14px;
	}
	.el-input__suffix{
		i{
			font-size: 22px;
		}
	}
}
.uhopbox{
	display: flex;
	height: 20px;
	align-items: center;
	width: 100%;
	margin: 5px 0 0 0;
	
	.rmps{
		flex: 1;
		line-height: normal;
		.el-checkbox__label{
			font-size: 14px!important;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #333;
		}
		.el-checkbox__inner{
			box-sizing: border-box;
			width: 18px;
			height: 18px;
			border-radius: 3px;
			border: 2px solid #fff;
			&::after{
				left:5px;
				top: 2px;
			}
		}
		.el-checkbox__input.is-checked{
			.el-checkbox__inner{
				background-color: #04AE70;
			}
		}
	}
	.is-checked{
		.el-checkbox__inner{
			border: 2px solid #04AE70;
		}
	}
	.forget{
		font-size: 16px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		color: #04AE70;
		text-decoration: underline;
		&:hover{
			cursor: pointer;
			color: #038052;
		}
	}
}

.el-dialog{
	&.loginDgBox{
		box-sizing: border-box;
		width: 510px;
		height: 475px;
		padding: 20px 55px;
		.el-dialog__header{
			border: 0;
		}
		.el-dialog__body{
			padding: 0;
		}
		.el-icon{
			font-size: 20px;
		}
	}
}

.fgDgBox{
	.dgTitle {
		display: flex;
		justify-content: center;
		margin: 16px 0 46px 0;
		span{
			display: inline-block;
			position: relative;
			z-index: 10;
			font-size: 26px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			color: #333333;
			padding: 0 0 15px 0;
			&::after{
				content: '';
				position: absolute;
				z-index: 10;
				left: 50%;
				bottom: 0;
				height: 5px;
				width: 100px;
				border-radius: 3px;
				background: linear-gradient(to right,#04AE70,#ffffff);
				margin-left: -48px;
			}
		}
	}
}

.cmformItem{
    display: flex;
	align-items: center;
	box-sizing: border-box;
    width: 100%;
    height: 52px;
    border-radius: 5px;
    border: 2px solid #DBE9F1;
	margin: 0 0 40px 0;
	.slbox{
		width: 95px;
		flex-shrink: 0;
		.el-input__inner{
			border: 0;
			font-size: 16px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
		}
	}
	.fgl{
		width: 1px;
		height: 26px;
		background: #DFDFDF;
		flex-shrink: 0;
	}
	.inputBox{
		flex: 1;
		flex-shrink: 0;
		input{
			box-sizing: border-box;
			width: 100%;
			height: 100%;
			border: 0;
			border-radius: 10px;
			padding: 0 23px;
			font-size: 16px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #333;
		}
	}
	.gtbtn{
		width: 134px;
		flex-shrink: 0;
		font-size: 16px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		color: #FF6400;
		text-align: center;
		cursor: pointer;
		&.gtbtn2{
			color: #999;
		}
	}
}
.forgetBnt{
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 56px;
	//background: url("@/assets/wjbtn.png") -27px top no-repeat;
	margin: 60px 0 0 0;
	font-size: 18px;
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	color: #FFFFFF;
	line-height: normal;
	padding: 0;
	background: #04AE70;
	border-radius: 5px;
	box-shadow: 0 10px 10px #D6F2E8;
	&:hover{
		cursor: pointer;
		opacity: 0.8;
	}
}

</style>
